<template>
  <div id="rtuList" class="wrapper pb-3 h-100" style="overflow-x: auto;">
    <el-form :inline="true" class="ur-form mb-3 d-flex pl-3" style="min-width:1330px;height: 54px;">
      <div class="d-flex align-items-center">
        责任区：
        <el-select class="w120 mr-2" v-model="rtu.regionId" slot="prepend" placeholder="请选择" size="small">
          <el-option label="全部" :value="-1"></el-option>
          <el-option v-for="(item,index) in regions" :key="index" :label="item.Name" :value="item.Id"></el-option>
        </el-select>
        分组：
        <el-select class="w130 mr-2" v-model="rtu.groupId" slot="prepend" placeholder="请选择" size="small">
          <el-option label="全部" :value="-1"></el-option>
          <el-option v-for="(item,index) in groups" :key="index" :label="item.GroupName" :value="item.Id"></el-option>
        </el-select>
        <el-input placeholder="请输入内容"  class="input-with-select w180 mr-2"  size="small" v-model="rtu.value">
          <el-button slot="append"  class="ur-btn ur-btn-primary" @click="query"><i class="iconfont icon-search"></i>查询</el-button>
        </el-input>
        <el-button class="ur-btn ur-btn-danger" @click="clearAlarm">清除报警</el-button>
        <el-button class="ur-btn ur-btn-danger ml-2" @click="clickFun(1)">重启</el-button>
        <el-button class="ur-btn ur-btn-danger ml-2" @click="clickFun(2)">开关灯时间</el-button>
        <el-button class="ur-btn ur-btn-primary ml-2" @click="exportData">导出</el-button>
        <!--        <el-button v-if="limits.indexOf('2_10_00_03')!=-1" class="ur-btn ur-btn-primary ml-2" @click="sMSConfig">短信批量设置</el-button>-->
      </div>
      <ul class="result_group ml-auto">
        <li><el-checkbox label="离线超过3天" name="type" v-model="unOnline" @change="rtu.qtype=null,QueryRtuMonitor()"></el-checkbox></li>
        <li :class="{'txt_blue4':rtu.qtype==3}" @click="unOnline=false,rtu.qtype=3,QueryRtuMonitor()"><i class="circle warning"></i>在线：
          <span class="electronicFont font24" style="color: #FFF944">{{count.OnLineCount}}</span></li>
        <li :class="{'txt_blue4':rtu.qtype==2}" @click="unOnline=false,rtu.qtype=2,QueryRtuMonitor()"><i class="circle info"></i>离线：
          <span class="electronicFont font24" style="color: #0099FF">{{count.OffLineCount}}</span></li>
<!--    <li :class="{'txt_blue4':rtu.qtype==21}" @click="unOnline=false,rtu.qtype=21,QueryRtuMonitor()"><i class="circle yellow mr-2"></i>明日开关灯异常</li>-->
        <li :class="{'txt_blue4':rtu.qtype==1}" @click="unOnline=false,rtu.qtype=1,QueryRtuMonitor()"><i class="circle error"></i>故障：
          <span class="electronicFont font24" style="color: #FF4444">{{count.AlarmCount}}</span></li>
      </ul>
    </el-form>
    <el-table class="ur-table" stripe :data="tableData3" style="min-width:1330px;margin:0 0 10px" :height="clientHeight-220" highlight-current-row
      @selection-change="selsChange" :cell-class-name="api.fixedCell" @sort-change="sortChange">
      <el-table-column type="selection" width="40" align="center"></el-table-column>
      <el-table-column align="center" type="index" :index="indexMethod" label="序号" width="40" fixed></el-table-column>
      <el-table-column sortable="custom" prop="No" label="箱号" width="90" align="center" fixed></el-table-column>
      <el-table-column sortable="custom" prop="AreaName" label="责任区" min-width="100" align="center" fixed></el-table-column>
      <el-table-column sortable="custom" prop="Location" label="安装地点" min-width="140" align="center"></el-table-column>
      <el-table-column sortable="custom" prop="Poles" label="单灯" width="60" align="center"></el-table-column>
      <el-table-column sortable="custom" prop="RtuManufacturer" label="设备厂家" min-width="90" align="center"></el-table-column>
      <el-table-column sortable="custom" prop="" label="告警状态" width="80" align="right">
        <template slot-scope="scope">
          <div v-if="scope.row.IsAlarm==0"><i class="circle blue"></i>正常</div>
          <div v-else @click="alarm(scope.$index,scope.row)" class="d-flex align-items-center justify-content-end">
            <i class="alarmIcon" :class="alarmClass(scope.row).class" :title="alarmClass(scope.row).txt"></i>报警
          </div>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="" label="运行状态" align="center"  width="90">
        <template slot-scope="scope">
          <template v-if="scope.row.RunState==0"><i class="circle success"></i>正常</template>
          <template v-else><i class="circle yellow"></i>故障</template>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="" label="在线状态" align="center"  width="90">
        <template slot-scope="scope">
          <template v-if="scope.row.Online==0"><i class="circle Violet"></i>离线</template>
          <template v-else><i class="circle  success"></i>在线</template>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="OnTime" label="开灯时间"  width="100" align="center"></el-table-column>
      <el-table-column sortable="custom" prop="OffTime" label="关灯时间" width="100"  align="center"></el-table-column>
      <el-table-column sortable="custom" prop="OnTime1" label="明日开灯"  width="90" align="center"></el-table-column>
      <el-table-column sortable="custom" prop="OffTime1" label="明日关灯" width="90"  align="center"></el-table-column>
      <el-table-column sortable="custom" prop="LastUpdateTime" label="采集时间" align="center" width="150"></el-table-column>
      <el-table-column sortable="custom" label="离线天数" align="center" min-width="90">
        <template slot-scope="scope">
          <span class="text-danger" v-if="scope.row.Online==0&&scope.row.LastUpdateTime">{{scope.row.OffLineDays}}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="DevAddr" label="设备地址" width="160" align="center"></el-table-column>
<!--      v-if="limits.indexOf('2_05_01_09')!=-1" -->
      <el-table-column prop="toDayEnergy" label="今日电能" align="center" min-width="70">
      </el-table-column>
<!--      limits.indexOf('2_05_01_09')!=-1?240:180-->
      <el-table-column label="详情" :width="180" align="center">
        <template slot-scope="scope">
          <div class="d-flex">
<!--v-if="limits.indexOf('2_05_01_09')!=-1"
v-if="limits.indexOf('2_05_01_04')!=-1"
v-if="limits.indexOf('2_10_00_03')!=-1"-->
            <!--<el-button class="ur-btn ur-btn-danger d-inline-block" @click="look(scope.$index,scope.row,'energy')">
              <i class="iconfont icon-xianshi "></i>抄表
            </el-button>-->
            <el-button class="ur-btn ur-btn-primary d-inline-block" @click="look(scope.$index,scope.row,'info')">
              <i class="font18 iconfont icon-xianshi" ></i>查看
            </el-button>
            <el-button class="ur-btn ur-btn-primary d-inline-block" @click="look(scope.$index,scope.row,'info')">
              <i class="font18 iconfont icon-setting" ></i>短信设置
            </el-button>
          </div>
         </template>
      </el-table-column>
      <el-table-column label="在线时长" width="80" align="center">
        <template slot-scope="scope">
<!--          v-if="limits.indexOf('2_05_01_06')!=-1"-->
          <el-button class="ur-btn ur-btn-success d-inline-block" @click="look(scope.$index,scope.row,'ontime')">
            <i class="font18 iconfont icon-xianshi" ></i>查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column  label="操作" width="85" align="center">
        <template slot-scope="scope">
<!--          &&limits.indexOf('3_01_01_04')!=-1-->
          <el-button v-if="scope.row.Operation==1"  class="ur-btn ur-btn-danger d-inline-block" @click="order(scope.$index,scope.row)">
            <i class="font18 iconfont icon-anzhuangweihu" ></i>工单
          </el-button>
          <template v-else-if="scope.row.Operation==2">已派工</template>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="float-right" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
    :page-sizes="[100,200,500,1000]" :page-size="pageSize" layout="total, sizes, prev, pager, next ,jumper" :total="total">
    </el-pagination>
    <el-dialog class="ur-form-dialog" v-el-drag-dialog title="查看详情" :visible.sync="detailDig" width="600px" @close="closeDetailDialog(false)">
      <rtulistdetails v-if="detailDig" @closeDetailDialog="closeDetailDialog($event)" :rtuId="rtuId" :boxImei="boxImei" :box="curBox"></rtulistdetails>
    </el-dialog>
    <el-dialog class="ur-form-dialog" v-el-drag-dialog title="生成工单" :visible.sync="workDig" width="750px"  center @close="closeWorkDialog(false)">
      <rtulistwork v-if="workDig" @closeWorkDialog="closeWorkDialog($event)" @WorkDialog="WorkDialog($event)" :areas="regions" :data="data"></rtulistwork>
    </el-dialog>
    <el-dialog class="ur-form-dialog" v-el-drag-dialog title="历史报警详情" :visible.sync="alarmDig" width="840px"  @close="closealarmDialog(false)">
      <rtulistalarm v-if="alarmDig" @closealarmDialog="closealarmDialog($event)"  :data="data" :type="1"></rtulistalarm>
    </el-dialog>
    <el-dialog class="ur-form-dialog" v-el-drag-dialog title="在线时长" :visible.sync="onTimeDig" width="550px" top="12%" center @close="onTimeDig=false">
      <template v-if="onTimeDig">
        <light-on-time :devAddr="boxImei" ></light-on-time>
      </template>
    </el-dialog>

<!--    重启结果-->
    <el-dialog class="ur-form-dialog" v-el-drag-dialog title="重启结果" :visible.sync="operateResultDig" width="700px" top="12%" center @close="operateResultDig=false">
      <el-table ref="rtuTable" :data="resultData" style="width: 700px" :height="500" highlight-current-row>
        <el-table-column align="center" type="index" :index="indexMethod" label="序号" width="50"></el-table-column>
        <el-table-column prop="No" label="控制箱编号" width="90" align="center"></el-table-column>
        <el-table-column prop="DevAddr" label="设备地址" width="160" align="center"></el-table-column>
        <el-table-column prop="result" label="下发结果" width="160" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.result==1">
              <i class='circle success'></i>成功
            </template>
            <template v-else-if="scope.row.result===0"><i class="circle error" ></i>失败</template>
            <template v-else>{{scope.row.result}}</template>
          </template>
        </el-table-column>
        <el-table-column prop="resultInfo" label="失败原因"  align="center"></el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog class="ur-form-dialog" v-el-drag-dialog :title="dialogTitle" :visible.sync="pwdDig" width="390px" top="20%">
      <div class="p-4" v-if="pwdDig">
        <div class="form-inline">
          <label>操作密码：</label>
          <el-tooltip class="item" :content="errors.first('pwd')" :value="errors.has('pwd')" :manual="true">
            <el-input type="password" size="small" class="w180" :class="{'is-error':errors.has('pwd')}" v-model="operatePwd" v-validate="'required'" name="pwd"></el-input>
          </el-tooltip>
          <el-button class="ur-btn w75 ml-3" :class="{'ur-btn-primary':!btnState}" type="info" @click="callFun" :disabled="btnState"><i class="iconfont icon-queding"></i>下发</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog class="ur-form-dialog" v-el-drag-dialog :title="sels.length>1?'短信批量设置':curBox.No+'——短信配置'" :visible.sync="showSMSConfig" width="700px" top="6%"  @close="closeSmsConfig">
      <template v-if="showSMSConfig">
        <sms-push-config :boxs="sels" ></sms-push-config>
      </template>
    </el-dialog>

  </div>
</template>

<script>
  import elDragDialog from 'directive/el-dragDialog'
  import rtulistalarm from './rtu-list-alarm'
  import rtulistdetails from './rtu-list-details'
  import rtulistwork from './rtu-list-work'
  import lightOnTime from './light-on-time'
  import api from 'api/api'
  import {mapState} from 'vuex'
  import fetch from 'api/fetch'
  import smsPushConfig from './sms-push-config'
  import Data from './data/data'

  export default {
    directives:{
      elDragDialog
    },
    components: {
      rtulistdetails,
      rtulistwork,
      rtulistalarm,
      lightOnTime,
      smsPushConfig
    },
    props: {},
    data() {
      return {
        detailDig: false,
        workDig: false,
        alarmDig: false,
        onTimeDig:false,
        operateResultDig:false,
        pwdDig:false,
        dialogTitle:'',
        operatePwd:'',
        resultData:[],
        btnIndex:1,
        total: 0,
        currentPage: 1,
        pageSize:100,
        search: '',
        tableIndex:"",
        tableData3: [],
        multipleSelection: [],
        rtuId: "",
        boxImei: "",
        data: "",
        count:{AlarmCount:10,OffLineCount:100,OnLineCount:100},
        sels:[],
        regions:[],
        groups:[],
        rtu:{regionId:-1,groupId:-1,value:'',qtype:null},
        curBox:{},
        timer:null,
        api:api,
        unOnline:false,
        alarmIcon:{1:3,2:2,3:1},//1:紧急 2:次紧急 3：一般
        sortType:0,
        sortMode:0,
        showSMSConfig:false
      }
    },
    watch: {
      rtu:{
        handler(newVal,oldVal){
          this.currentPage=1
        },
        deep:true
      }
    },
    computed: mapState({
      clientHeight: state => state.comm.clientHeight,
      clientWidth: state => state.comm.clientWidth,
      limits:state=>state.user.userInfo.limits,
      btnState:state=>state.user.btnState,
    }),
    methods: {
      //短信设置
      sMSConfig(){
        debugger
        if(!this.sels.length){
          return this.$message.warning({showClose:true,message:'未选择设备'})
        }
        this.showSMSConfig=true
      },
      closeSmsConfig(){
        this.showSMSConfig=false
        this.sels=[]
        localStorage.removeItem('boxSels')
      },
      sortChange(o){
        let lable=o.column['label']
        const columnObj={1:'箱号',2:'责任区',3:'安装地点',4:'单灯',5:'设备厂家',6:'告警状态',7:'运行状态',8:'在线状态',9:'开灯时间'
          ,10:'关灯时间',11:'明日开灯',12:'明日关灯',13:'采集时间',14:'离线天数',15:'设备地址'}
        let keys = Object.keys(columnObj)
        let values = Object.values(columnObj)
        let index = values.indexOf(lable)
        this.sortMode = o.order == "descending" ? 1 : 0
        this.sortType = keys[index]
        this.QueryRtuMonitor()
      },
      clickFun(v){
        this.btnIndex=v
        this.resultData=[]
        switch (v){
          case 1:
            this.pwdDig=true
            return this.dialogTitle='重启'
          case 2:
            this.pwdDig=true
            return this.dialogTitle='读取开光灯时间'
        }
      },
      callFun() {
        let url = '', data = ''
        let callIndex = this.btnIndex
        this.resultData=JSON.parse(JSON.stringify(this.sels))
        let rows=[]
        if(this.btnIndex==1){
          rows=this.resultData
        }else{
          rows=this.sels
        }
        let isOperate=false
        if (this.sels.length == 0) return this.$message.warning('未选择控制箱')
        this.$validator.validateAll().then((res) => {
          if (res) {
            this.$store.commit('user/SET_USER_PWD', this.operatePwd)
            this.$store.commit('user/SET_BTN_STATE', true)
            let pIndex = 1
            rows.map((box, index, arr) => {
              data = {boxDevAddr: box.DevAddr}
             if (callIndex == 1) {//重启
                url = '/Communication/Rtu/RtuReboot'
              }else if (callIndex == 2) {//读取时钟
                url = '/Communication/Rtu/OnOffTimeQuery'
                data = {boxDevAddr: box.DevAddr,month:(new Date().getMonth()+1),startDay:new Date().getDate(),days:2}
              }
              api.fetchSimple(url, data)
                  .then(r => {
                    if (r.err) {
                      box.result = 0
                      box.resultInfo = r.err
                    } else {
                      if(this.btnIndex==2&&r.data.OnOffTime.length){//开关灯时间
                        let times=r.data.OnOffTime[0].split(',')//今天
                        box.OnTime=times[0]
                        box.OffTime=times[1]
                        let times1=r.data.OnOffTime[1].split(',')//明天
                        box.OnTime1=times1[0]
                        box.OffTime1=times1[1]
                      }
                      box.result = 1
                      box.resultInfo = '/'
                    }
                    let pcen = Math.round(pIndex / arr.length * 100) > 100 ? 100 : Math.round(pIndex / arr.length * 100)
                    // this.updateBar(pcen)
                    pIndex++
                    if (pcen == 100) {
                      this.$store.commit('user/SET_BTN_STATE', false)
                      this.pwdDig= false
                      if(this.btnIndex==1){//重启
                        this.operateResultDig=true
                      }else if(this.btnIndex==2){//开光灯时间
                        this.tableData3.splice(0,0)
                        this.$message.success({showClose:true,message:'查询成功'})
                      }
                    }
                  })
            })
          }
        })
      },
      changeAlarmType(type){
        this.unOnline=false
        this.rtu.qtype=type
        this.QueryRtuMonitor()
      },
      alarmClass(row){
        if(row.AlarmType==1){
          switch (row.Erc) {
            case 10:
              return {class:'erc10',txt:'RTU失电'}
            case 380:
              return {class:'erc380',txt:'断线'}
            case 60:
              return {class:'erc60',txt:'开灯异常'}
            case 70:
              return {class:'erc70',txt:'关灯异常'}
            default:
              return {class:'alarm1',txt:'紧急报警'}
          }
        }else if(row.AlarmType==2){
          return {class:'alarm2',txt:'次紧急报警'}
        }else{
          return {class:'alarm3',txt:'一般报警'}
        }
      },
      query(){
        this.currentPage=1
        this.rtu.qtype=null
        this.QueryRtuMonitor()
        this.RtuMonitorStatistics()
      },
      exportData(){
        api.fetchFile('/Monitor/ExportRtuMonitor', this.rtu)
          .then(r => {
            fetch.saveFile(r,'RTU监控列表',['',''])
          })
      },
      clearAlarm(){
        if (this.sels.length) {
          if(this.limits.indexOf('2_05_01_03')==-1) return this.$message.error({showClose:true,message:'该用户无权限操作'})
          this.$confirm('确定删除勾选RTU报警？', '提示', {type: 'warning'})
            .then(() => {
              this.sels.map(r => {
                api.fetchSimple('/Monitor/ClearRtuAlarmById', {rtuId: r.RtuId})
                    .then(r => {
                      if (r != '') {
                        this.$refs.rtuTable.clearSelection()//清空选择
                      }
                    })
              })
            })
        } else {
          if(this.limits.indexOf('2_05_01_07')==-1) return this.$message.error({showClose:true,message:'该用户无权限操作'})
          //, center: true
          this.$confirm('确定删除所有RTU报警？', '提示', {type: 'warning'})
            .then(() => {
              api.fetchSimple('/Monitor/ClearAllRtuAlarm', {})
            })
        }
      },
      selsChange(sels){
        this.sels=sels
        let boxIds=[]
        sels.map(box=>{
          boxIds.push(box.BoxId)
        })
        if(boxIds.length){
          localStorage.setItem('boxSels',JSON.stringify(sels))
          localStorage.setItem('boxIds',JSON.stringify(boxIds))
        }
      },
      indexMethod(index) {
        return index + 1;
      },
      async look(index,data,page) {
        debugger
        this.curBox=data
        this.rtuId = data.RtuId
        this.boxImei = data.DevAddr
        if (page == 'info') {//详情
          // if(data.Online==0) return this.$message.warning({showClose:true,message:'不在线'})
          this.detailDig = true
        }
        else if (page == 'ontime') {//在线时长
          this.onTimeDig = true
        }
        else if(page=='energy'){
          let res=await api.fetchSimple('/Monitor/GetTodayEnergy',{rtuId:data.RtuId})
          this.$set(data,'toDayEnergy',res.data.toFixed(2))
        }
        else if(page=='smsConfig'){
          this.sels=[data]
          this.showSMSConfig=true
        }
      },
      closeDetailDialog(v) {
        this.detailDig = v
      },
      order(index, data) {
        this.tableIndex = index;
        this.rtuId = data.RtuId
        this.workDig = true
        this.data = data
      },
      closeWorkDialog(v) {
        this.workDig = v
      },
      closealarmDialog(v) {
        this.alarmDig = v
      },
      WorkDialog(v) {
        let self = this;
        if (v) {
          self.tableData3[self.tableIndex].Operation = 2
        }
      },
      alarm(index, data) {
        this.data = data;
        this.alarmDig = true;
      },
      //RTU监控查询
      QueryRtuMonitor() {
        if(this.unOnline){
          this.rtu.qtype=4
        }
        let rtu = Object.assign({}, this.rtu)
        rtu = Object.assign(rtu,{pageNo: this.currentPage, pageSize: this.pageSize, onlyState: 0,sortType:this.sortType,sortMode:this.sortMode})
        let _this=this
        // api.fetchSimple('/Monitor/QueryRtuMonitor',rtu).then(async r => {
        let r = Data
        if (!r.data) {
          this.total = 0
          this.tableData3 = []
          return
        }
        _this.total = r.total || 0
        if (_this.tableData3.length != r.data.length) {
          _this.tableData3 = r.data
        } else {
          (r.data).map((box, index, arr) => {
            for (let key in box) {
              _this.tableData3[index][key] = box[key]
            }
          })
        }
        // })
      },
      RtuMonitorStatistics() {
        api.fetchSimple('/Monitor/RtuMonitorStatistics', this.rtu).then(r => {
          this.count=r.data
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.currentPage = 1
        this.QueryRtuMonitor()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.QueryRtuMonitor()
      },
      queryRegion(){
      },
      queryGroup(){
      }
    },
    created() {
      let self = this;
      this.queryRegion()
      this.queryGroup()
      this.sels=JSON.parse(localStorage.getItem('boxSels'))||[]
      this.QueryRtuMonitor()
      // this.RtuMonitorStatistics()
      //界面刷新周期3000毫秒
   /*   this.timer = setInterval(function () {
        self.QueryRtuMonitor()
        self.RtuMonitorStatistics()
      }, 3*1000)*/
    },
    mounted() {
    },
    beforeRouteLeave(to, from, next){
      clearInterval(this.timer)
      this.timer=null
      next()
    }
  }
</script>
<style lang="stylus" rel="stylesheet/stylus">
  .Violet{background:#9CB0C6}
  .blue{background:#0c8eec}
  .blue1 {color: #0c8eec}
  .yellow {background: yellow}
  #rtuList .el-table .cell{padding-left: 0px !important;padding-right: 0px !important; }
</style>
